﻿using RichTextBoxCtrl;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Admin;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.BusinessLogic.Member;
using OpenSoftStore.Client.UIL.UserControls;
using OpenSoftStore.Orm.Model;
namespace OpenSoftStore.Client.Common
{
    public class SPACommon
    {
        public static AdminLogic LgcAdmin = new AdminLogic();
        public static ComboLogic LgcCombo = new ComboLogic();
        public static DinnerLogic LgcDinner = new DinnerLogic();
        #region Uilities
        ///  <summary>
        /// 当控件有子控件时，需要用递归的方法遍历，才能全部列出控件上的控件
        ///  </summary>
        ///  <param name="control">要遍历的控件</param>>
        /// <param name="controls"></param>
        /// <returns></returns>
        private static void GetControl(Control control, List<Control> controls)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                var tempcontrol = control.Controls[i];
                if (tempcontrol.HasChildren)
                    GetControl(tempcontrol, controls);
                controls.Add(tempcontrol);
            }
        }
        #endregion

        #region Caches

        private static Dictionary<string, PropertyInfo[]> _classesDictionary=new Dictionary<string, PropertyInfo[]>();

        private static PropertyInfo[] GetProperties(Type type)
        {
            if (!_classesDictionary.Any(m => m.Key == type.Name))
            {
                PropertyInfo[] temproperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                _classesDictionary.Add(type.Name, temproperties);
            }
            return _classesDictionary[type.Name];
        }

        public static void CopyPropertiesFrom(object destObject, object sourceObject)
        {
            PropertyInfo[] destProperties = GetProperties(destObject.GetType());
            PropertyInfo[] sourceProperties = GetProperties(sourceObject.GetType());

            foreach (PropertyInfo p in destProperties)
            {
                if (p == null) continue;
                var sourceProperty = sourceProperties.FirstOrDefault(m => m.Name == p.Name);
                if (sourceProperty == null) continue;
                object dstV = p.GetValue(destObject, null);
                object srcV = sourceProperty.GetValue(sourceObject, null);
                //if (srcV == null) continue;
                if (dstV != null && srcV != null)
                    if (dstV.ToString() == srcV.ToString()) continue;
                p.SetValue(destObject, srcV, null);
            }
        }
        #endregion

        #region Motheds

        /// <summary>
        /// DataTable 转换为List 集合
        /// </summary>
        /// <typeparam name="TResult">类型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<TResult> ToList<TResult>(DataTable dt) where TResult : class,new()
        {
            var prlist = new List<PropertyInfo>();
            Type t = typeof(TResult);
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            var oblist = new List<TResult>();
            foreach (DataRow row in dt.Rows)
            {
                var ob = new TResult();
                prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
                oblist.Add(ob);
            }
            return oblist;
        }
        /// <summary>
        /// List 集合转换为一个DataTable
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        ///// <param name="value"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<TResult>(IEnumerable<TResult> value) where TResult : class
        {
            var pList = new List<PropertyInfo>();
            Type type = typeof(TResult);
            var dt = new DataTable();
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (var item in value)
            {
                DataRow row = dt.NewRow();
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                dt.Rows.Add(row);
            }
            return dt;
        }
        #region SetUiStyle

        public static void SetUiStyle(Control control)
        {
            var controls = new List<Control>();
            GetControl(control, controls);
            foreach (Control controlItem in controls)
            {
                switch (controlItem.GetType().Name)
                {
                    case "YhSoftTabControl":
                    case "TabControl":
                        var itemTabControl = controlItem as TabControl;
                        SetTabControlStyle(itemTabControl);
                        continue;
                    case "YhSoftDataGridView":
                    case "DataGridView":
                        var itemDataGridView = controlItem as DataGridView;
                        SetDataGridStyle(itemDataGridView);
                        continue;
                    case "YhSoftComboBox":
                    case "ComboBox":
                        var itemComboBox = controlItem as ComboBox;
                        SetComboBoxStyle(itemComboBox);
                        continue;
                    case "Panel":
                        var itemPanel = controlItem as Panel;
                        SetPanleStyle(itemPanel);
                        continue;
                    case "YhSoftToolStrip":
                    case "ToolStrip":
                        var itemToolStrip = controlItem as ToolStrip;
                        SetToolStripStyle(itemToolStrip);
                        continue;
                }
            }
        }

        public static void SetDataGridStyle(DataGridView dgv, int columnHeadersHeight = 45, int rowTemplateHeight = 30)
        {
            dgv.RowHeadersVisible = true;

            dgv.RowHeadersWidth = dgv.Width >= 500 ? 40 : 28;
            dgv.AutoGenerateColumns = false;
            dgv.EnableHeadersVisualStyles = false;
            dgv.AllowDrop = true;
            dgv.AllowUserToOrderColumns = true;
            dgv.AllowUserToResizeColumns = true;
            dgv.AllowUserToResizeRows = true;
            dgv.ColumnHeadersHeight = columnHeadersHeight;
            dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dgv.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(242, 242, 242);
            dgv.RowTemplate.DefaultCellStyle.SelectionBackColor = Color.FromArgb(70, 141, 75);
            //dgv.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.FromArgb(153, 153, 153);
            dgv.RowTemplate.DefaultCellStyle.SelectionForeColor = Color.FromArgb(255, 255, 255);
            dgv.RowTemplate.Height = rowTemplateHeight;

            dgv.RowPostPaint += DgvGrid_RowPostPaint;
            dgv.DataError += DgvGrid_DataError;
            DgvGrid_Paint(dgv);
            //string[] SummaryColumns=new string[3];
            //ShowSummary(dgv);
        }

        private static void DgvGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var dgv = sender as DataGridView;
            if (dgv == null) return;
            if(e.RowIndex%2==0){
                dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(248, 248, 248);
            }

            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                 e.RowBounds.Location.Y,
                 dgv.RowHeadersWidth - 4,
                 e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dgv.RowHeadersDefaultCellStyle.Font,
                rectangle,
               Color.FromArgb(100, 100, 100),
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            dgv.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(70, 141, 75);

        }

        private static void DgvGrid_DataError(object sender, DataGridViewDataErrorEventArgs e) { }

        private static void DgvGrid_Paint(DataGridView dgv)
        {
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                
                var item = dgv.Columns[i];
                item.SortMode = DataGridViewColumnSortMode.Automatic;
                var valueType = "";
                if (item.ValueType != null)
                    valueType = dgv.Columns[i].ValueType.ToString().ToLower();

                if (item.Width < 120)
                {
                    if (item.HeaderText.Length <= 2)
                        item.Width = 60;
                    else if (item.HeaderText.Length >= 3 && item.HeaderText.Length <= 4)
                        item.Width = 80;
                    else
                        item.Width = 100;
                }
                switch (valueType)
                {
                    case "system.string":
                        continue;
                    case "system.decimal":
                        if (item.HeaderText.Contains("价") || item.HeaderText.Contains("额") ||
                            item.HeaderText.Contains("收") || item.HeaderText.Contains("款") || item.HeaderText.Contains("值") || item.HeaderText.Contains("优惠"))
                        {
                            item.DefaultCellStyle.Format = "C2";
                            item.Width = 100;
                        }
                        else
                            item.DefaultCellStyle.Format = "N2";
                        item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        continue;
                    case "system.int32":
                        if (item.HeaderText.Contains("价") || item.HeaderText.Contains("额") || item.HeaderText.Contains("款") || item.HeaderText.Contains("值"))
                            item.DefaultCellStyle.Format = "C0";
                        else
                            item.DefaultCellStyle.Format = "N0";
                        item.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        continue;
                    case "system.datetime":
                        if (item.HeaderText.Contains("时间"))
                            item.Width = 110;
                        else
                            item.Width = 80;
                        continue;
                    default:
                        continue;
                }

            }
        
 
        }

        /// <summary>
        /// 显示DataGridView的统计信息
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="SummaryColumns">要统计的列名称或数据源绑定列名称</param>
        public static void ShowSummary(DataGridView dgv, string[] SummaryColumns=null)
        {
            SummaryControlContainer summaryControl = new SummaryControlContainer(dgv, SummaryColumns);
            dgv.Controls.Add(summaryControl);
            //dgv.Tag = summaryControl;
            //summaryControl.BringToFront();
            summaryControl.Show();
            summaryControl.Width = dgv.Width;
        }
        /// <summary>
        /// 显示DataGridView的统计信息
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="DisplaySumRowHeader">是否显示合计行标题</param>
        /// <param name="SumRowHeaderText">合计列标题</param>
        /// <param name="SumRowHeaderTextBold">合计列标题用粗体显示</param>
        /// <param name="SummaryColumns">要统计的列名称或数据源绑定列名称</param>
        public static void ShowSummary(DataGridView dgv, bool DisplaySumRowHeader, string SumRowHeaderText, bool SumRowHeaderTextBold, string[] SummaryColumns)
        {
            SummaryControlContainer summaryControl = new SummaryControlContainer(dgv, DisplaySumRowHeader, SumRowHeaderText, SumRowHeaderTextBold, SummaryColumns);
            dgv.Controls.Add(summaryControl);
            //dgv.Tag = summaryControl;
            summaryControl.BringToFront();
            summaryControl.Show();
        }

        public static void SetTabControlStyle(TabControl tb)
        {
            tb.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            tb.HotTrack = true;
            tb.ItemSize = new System.Drawing.Size(120, 30);
        }

        public static void SetComboBoxStyle(ComboBox cmb)
        {
            switch (cmb.Name)
            {
                case "cmbAdminId":
                case "cmbAdmin":
                      cmb.DataSource = LgcAdmin.GetAdminViewFast();
                      cmb.DisplayMember = "Name";
                      cmb.ValueMember = "Id";
                      cmb.Text = "超级管理员";
                    break;
                case "cmbDinnerId":
                case "cmbDinner":
                    cmb.DataSource = LgcDinner.GetDinners();
                    cmb.DisplayMember = "Name";
                    cmb.ValueMember = "Id";
                    break;
                case "cmbShop":
                    cmb.DataSource = LgcAdmin.GetShops();
                    cmb.DisplayMember = "Name";
                    cmb.ValueMember = "Id";
                    break;
                case "cmbSex":
                    cmb.DisplayMember = "DisplayText";
                    cmb.ValueMember = "Value1";
                    cmb.DataSource = LgcCombo.GetComboByBuzType("Sex");
                    break;
                case "cmbSkinType":
                    cmb.DisplayMember = "DisplayText";
                    cmb.ValueMember = "Value1";
                    cmb.DataSource = LgcCombo.GetComboByBuzType("SkinType");
                    break;
            }

        }

        public static void SetPanleStyle(Panel pnl)
        {
            if (pnl.Name.Contains("Total")) pnl.Height = 40;
        }

        public static void SetToolStripStyle(ToolStrip tl)
        {
            tl.BackColor = System.Drawing.Color.White;
            tl.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            tl.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
            tl.Height = 30;
        }

        #endregion

        #region Export
        /// <summary>
        /// datagridview导出Excel(以流的方式) 
        /// </summary>
        public static void ExportToExcel(DataGridView dgv, string fileName = "")
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Execl files (*.xls)|*.xls",
                FilterIndex = 0,
                RestoreDirectory = true,
                CreatePrompt = true,
                Title = "保存为Excel文件",
                FileName = fileName + DateTime.Now.ToString("yyyyMdhhmm")
            };
            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"

            Stream myStream = saveFileDialog.OpenFile();
            var sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string columnTitle = "";
            try
            {
                //写入列标题
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        columnTitle += "\t";
                    }
                    columnTitle += dgv.Columns[i].HeaderText;
                }
                sw.WriteLine(columnTitle);

                //写入列内容
                for (int j = 0; j < dgv.Rows.Count; j++)
                {
                    string columnValue = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            columnValue += "\t";
                        }
                        if (dgv.Rows[j].Cells[k].Value == null)
                            columnValue += "";
                        else
                            columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                    }
                    sw.WriteLine(columnValue);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        public static void ExportToExcel(TreeView tv, string fileName = "")
        {
            var trees=new List<Tree>();
            CheckAllChildNodes(tv.TopNode, true, trees);
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Execl files (*.xls)|*.xls",
                FilterIndex = 0,
                RestoreDirectory = true,
                CreatePrompt = true,
                Title = "保存为Excel文件",
                FileName = fileName + DateTime.Now.ToString("yyyyMdhhmm")
            };
            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"

            Stream myStream = saveFileDialog.OpenFile();
            var sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string columnTitle = "";
            try
            {
                columnTitle += "系统编号" + "\t" + "父节点" + "\t" + "功能" + "\t";
                sw.WriteLine(columnTitle);

                //写入列内容
                string columnValue = "";
                foreach (var tree in trees)
                {
                    columnValue = tree.Name + "\t" + tree.ParentText + "\t" + tree.Text + "\t";
                    sw.WriteLine(columnValue);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }
        #endregion

        #region Tree
        public class Tree
        {
            public string Name{get;set;}
            public string Text{ get; set; }
            public string ParentText{ get; set; }
        }

        public static void SetTreeStyle(TreeView tv)
        {
            tv.AfterSelect += TvAfterSelect;
        }

        public static void TvAfterSelect(object sender, TreeViewEventArgs e)
        {
            var tv = sender as TreeView;
            if (tv.SelectedNode == tv.Nodes[0])
            {
                tv.SelectedNode.BackColor = Color.FromArgb(255, 49, 106, 197);
                tv.SelectedNode.ForeColor = Color.White;
            }
            else
            {
                tv.Nodes[0].BackColor = tv.BackColor;
                tv.Nodes[0].ForeColor = Color.Black; 
                tv.SelectedNode.BackColor = tv.BackColor;
                tv.SelectedNode.ForeColor = Color.Black; 
            }
        }

        public static void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked, List<T_AdminPowerMapp> adminPowerMapps)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                var tree = new T_AdminPowerMapp();
                if (node.Checked == nodeChecked)
                {
                    tree.TreeId = node.Name;
                    //tree. = node.Text;
                    //tree.ParentText = node.Parent.Text;
                    adminPowerMapps.Add(tree);
                }
                if (node.Nodes.Count > 0)
                {
                    CheckAllChildNodes(node, nodeChecked, adminPowerMapps);
                }
            }
        }

        public static void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked, List<Tree> trees)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                var tree = new Tree();
                if (node.Checked == nodeChecked)
                {
                    tree.Name = node.Name;
                    tree.ParentText = node.Parent.Text;
                    tree.Text = node.Text;
                    trees.Add(tree);
                }
                if (node.Nodes.Count > 0)
                {
                    CheckAllChildNodes(node, nodeChecked, trees);
                }
            }
        }

        public static void CheckAllChildNodes(TreeNode treeNode, bool nodeChecked, List<T_Tree> trees)
        {
            foreach (TreeNode node in treeNode.Nodes)
            {
                var tree = new T_Tree();
                if (node.Checked == nodeChecked)
                {
                    tree.Id = node.Name;
                    tree.Name = node.Text;
                    tree.ParentId = node.Parent.Name;
                    trees.Add(tree);
                }
                if (node.Nodes.Count > 0)
                {
                    CheckAllChildNodes(node, nodeChecked, trees);
                }
            }
        }
        #endregion

        #region ControlAndObjectChange
        public static void SetRichTextBoxExtToControlValue(Control control, RichTextBoxExt obj)
        {
            var controls = new List<Control>();
            GetControl(control, controls);
             foreach (var controlItem in controls)
            {
                switch (controlItem.GetType().Name)
                {
                    case "CheckBox":
                        if (controlItem.Tag == null) continue;
                        var itemCheckBox = controlItem as CheckBox;
                        var getValue = obj.GetValue(itemCheckBox.Tag.ToString().Replace(" ",""),RichTextBoxExt.FindType.Auto);
                        if (string.IsNullOrEmpty(getValue)) continue;
                        var value = getValue.ToString();
                        if (value == "是" || value == "1")
                            itemCheckBox.Checked = true;
                        else
                            itemCheckBox.Checked = false;
                        continue;
                    case "TextBox":
                        //var itemTextBox = controlItem as TextBox;
                        if (controlItem.Tag == null) continue;
                        var getTextBox = obj.GetValue(controlItem.Tag.ToString().Replace(" ", ""), RichTextBoxExt.FindType.Auto);
                        if (string.IsNullOrEmpty(getTextBox)) continue;
                        controlItem.Text = getTextBox.ToString();
                        continue;
                    case "NumericUpDown":
                        if (controlItem.Tag == null) continue;
                        var itemNumericUpDown = controlItem as UIL.UserControls.NumericUpDown;
                        var valueNumericUpDown = obj.GetValue(itemNumericUpDown.Tag.ToString().Replace(" ", ""), RichTextBoxExt.FindType.Auto);
                        if (valueNumericUpDown == "") continue;
                        itemNumericUpDown.Value = Convert.ToDecimal(valueNumericUpDown);
                        continue;
                    case "YhSoftDateTimePicker":
                        if (controlItem.Tag == null) continue;
                        var itemYhSoftDateTimePicker = controlItem as OpenSoftStore.Client.UIL.UserControls.YhSoftDateTimePicker;
                        var valueYhSoftDateTimePicker = obj.GetValue(itemYhSoftDateTimePicker.Tag.ToString().Replace(" ", ""), RichTextBoxExt.FindType.Auto);
                        if (valueYhSoftDateTimePicker == "") continue;
                        itemYhSoftDateTimePicker.Value = Convert.ToDateTime(valueYhSoftDateTimePicker);
                        continue;
                    case "DateTimePicker":
                        if (controlItem.Tag == null) continue;
                        var itemDateTimePicker = controlItem as DateTimePicker;
                        var valueDataTimePricker = obj.GetValue(itemDateTimePicker.Tag.ToString().Replace(" ", ""), RichTextBoxExt.FindType.Auto);
                        if (valueDataTimePricker == "") continue;
                        itemDateTimePicker.Text = Convert.ToDateTime(valueDataTimePricker).ToString();
                        continue;
                    case "YhSoftComboBox":
                        if (controlItem.Tag == null) continue;
                        var itemYhSoftComboBox = controlItem as YhSoftComboBox;
                        var valueYhSoftComboBox = obj.GetValue(itemYhSoftComboBox.Tag.ToString().Replace(" ", ""), RichTextBoxExt.FindType.Auto);
                        if (valueYhSoftComboBox == "") continue;
                        var getYhSoftComboBox = valueYhSoftComboBox;
                        if (getYhSoftComboBox == null) getYhSoftComboBox = "";
                        itemYhSoftComboBox.Text = getYhSoftComboBox.ToString();
                        continue;
                    case "ComboBox":
                        if (controlItem.Tag == null) continue;
                        var itemComboBox = controlItem as ComboBox;
                        var valueComboBox = obj.GetValue(itemComboBox.Tag.ToString().Replace(" ", ""), RichTextBoxExt.FindType.Auto);
                        if (valueComboBox == "") continue;
                        itemComboBox.Text = valueComboBox;
                        continue;
                }
            }
        }

        public static void SetObjectToControlValue(Control control, Object obj)
        {
            var controls = new List<Control>();
            GetControl(control, controls);
            PropertyInfo[] properties = obj.GetType().GetProperties();
            foreach (var property in properties)
            {
                if (property.Name == "Id") continue;
                var data=controls.Where(m => m.Name.Length >= 3);
                var controlItem = data.FirstOrDefault(m => m.Name.Substring(3) == property.Name || m.Name.Substring(2) == property.Name || m.Name.Substring(1) == property.Name);
                if (controlItem == null) continue;
                switch (controlItem.GetType().Name)
                {
                    case "RichTextBox":
                        var itemRichTextBox = controlItem as RichTextBox;
                        var getRichTextBox = property.GetValue(obj, null);
                        if (getRichTextBox == null) getRichTextBox = "";
                        itemRichTextBox.Rtf = HttpUtility.UrlDecode(getRichTextBox.ToString().Replace("|", "%"), Encoding.UTF8);
                        continue;
                    case "RichTextBoxExt":
                        var itemRichTextBoxExt = controlItem as RichTextBoxExt;
                        var getRichTextBoxExt = property.GetValue(obj, null);
                        if (getRichTextBoxExt == null) getRichTextBoxExt="";
                        itemRichTextBoxExt.Rtf = HttpUtility.UrlDecode(getRichTextBoxExt.ToString().Replace("|", "%"), Encoding.UTF8);
                        continue;
                    case "YhSoftCheckBox":
                    case "CheckBox":
                        var itemCheckBox = controlItem as CheckBox;
                        var getValue = property.GetValue(obj, null);
                        var value = getValue == null ? "" : getValue.ToString();
                        if (value == "是" || value=="1")
                            itemCheckBox.Checked = true;
                        else
                            itemCheckBox.Checked = false;
                        continue;
                    case "TextBox":
                        var getTextBox = property.GetValue(obj, null);
                        if (getTextBox == null) getTextBox = "";
                        controlItem.Text = getTextBox.ToString();
                        continue;
                    case "NumericUpDown":
                        var itemNumericUpDown = controlItem as OpenSoftStore.Client.UIL.UserControls.NumericUpDown;
                        itemNumericUpDown.Value = Convert.ToDecimal(property.GetValue(obj, null));
                        continue;
                    case "YhSoftDateTimePicker":
                        var itemYhSoftDateTimePicker = controlItem as OpenSoftStore.Client.UIL.UserControls.YhSoftDateTimePicker;
                        if (property.GetValue(obj, null).ToString() == "0001/1/1 0:00:00") continue;
                        itemYhSoftDateTimePicker.Value = Convert.ToDateTime(property.GetValue(obj, null));
                        continue;
                    case "DateTimePicker":
                        var itemDateTimePicker = controlItem as DateTimePicker;
                        if (property.GetValue(obj, null).ToString() == "0001/1/1 0:00:00") continue;
                        itemDateTimePicker.Text = Convert.ToDateTime(property.GetValue(obj, null)).ToString();
                        continue;
                    case "YhSoftComboBox":
                        var itemYhSoftComboBox = controlItem as YhSoftComboBox;
                        var getYhSoftComboBox = property.GetValue(obj, null);
                        if (getYhSoftComboBox == null) getYhSoftComboBox = "";
                        itemYhSoftComboBox.Text = getYhSoftComboBox.ToString();
                        continue;
                    case "ComboBox":
                        var itemComboBox = controlItem as ComboBox;
                        itemComboBox.Text = property.GetValue(obj, null).ToString();
                        continue;
                }
            }
        }

        public static void SetControlToObjectValue(Control control, Object obj)
        {
            var controls = new List<Control>();
            GetControl(control, controls);
            PropertyInfo[] properties = obj.GetType().GetProperties();
            foreach (var property in properties)
            {
                if (property.Name == "Id") continue;
                var data = controls.Where(m => m.Name.Length >= 3);
                var controlItem = data.FirstOrDefault(m => m.Name.Substring(3) == property.Name || m.Name.Substring(2) == property.Name || m.Name.Substring(1) == property.Name);
                if (controlItem == null) continue;
                switch (controlItem.GetType().Name)
                {
                    case "RichTextBox":
                        var itemRichTextBox = controlItem as RichTextBox;
                        property.SetValue(obj, HttpUtility.UrlEncode(itemRichTextBox.Rtf, Encoding.UTF8).Replace("%", "|"), null);
                        continue;
                    case "RichTextBoxExt":
                        var itemRichTextBoxExt = controlItem as RichTextBoxExt;
                        property.SetValue(obj, HttpUtility.UrlEncode(itemRichTextBoxExt.Rtf, Encoding.UTF8).Replace("%", "|"), null);
                        continue;
                    case "YhSoftCheckBox":
                    case "CheckBox":
                        var itemCheckBox = controlItem as CheckBox;
                        if (itemCheckBox.Checked)
                            property.SetValue(obj, "是", null);
                        else
                            property.SetValue(obj, "否", null);
                        continue;
                    case "TextBox":
                        property.SetValue(obj, controlItem.Text.Trim(), null);
                        continue;
                    case "NumericUpDown":
                        var itemNumericUpDown = controlItem as OpenSoftStore.Client.UIL.UserControls.NumericUpDown;
                        property.SetValue(obj, itemNumericUpDown.Value, null);
                        continue;
                    case "YhSoftDateTimePicker":
                        var itemYhSoftDateTimePicker = controlItem as OpenSoftStore.Client.UIL.UserControls.YhSoftDateTimePicker;
                        property.SetValue(obj, itemYhSoftDateTimePicker.Value, null);
                        continue;
                    case "DateTimePicker":
                        var itemDateTimePicker = controlItem as DateTimePicker;
                        property.SetValue(obj, itemDateTimePicker.Value, null);
                        continue;
                    case "YhSoftComboBox":
                        var itemYhSoftComboBox = controlItem as YhSoftComboBox;
                        property.SetValue(obj, itemYhSoftComboBox.Text.Trim(), null);
                        continue;
                    case "ComboBox":
                        var itemComboBox = controlItem as ComboBox;
                        property.SetValue(obj, itemComboBox.Text.Trim(), null);
                        continue;
                }
            }
        }
        #endregion


        public static void SelectNextControl(Control control, KeyEventArgs e)
        {
            var findForm = control.FindForm();
            if (findForm == null) return;
            if (e.KeyCode == Keys.Enter)
            {
                findForm.SelectNextControl(control, true, true, true, true);
            }
            if (control is CheckBox)
            {
                if (e.KeyCode == Keys.Add)
                {
                    var checkBox = control as CheckBox;
                    checkBox.Checked = true;
                }
                if (e.KeyCode == Keys.Subtract)
                {
                    var checkBox = control as CheckBox;
                    checkBox.Checked = false;
                }
            }
        }

        public static string Encode(string str)
        {
            var sb = new StringBuilder();
            byte[] byStr = Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            foreach (byte t in byStr)
            {
                sb.Append(@"%" + Convert.ToString(t, 16));
            }

            return (sb.ToString());
        }

        //public static string Decode(string str)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
        //    for (int i = 0; i < byStr.Length; i++)
        //    {
        //        sb.Append(@"%" + Convert.ToString(byStr[i], 16));
        //    }

        //    return (sb.ToString());
        //}

        #endregion
    }
}
